/**
 *
 */
package com.feizhi.common.search.index.action;

import java.io.IOException;
import java.util.concurrent.atomic.AtomicBoolean;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;

import com.feizhi.common.search.exception.SearchException;
import com.feizhi.common.search.index.LuceneWork;

/**
 * @author shuaqiu
 */
@Component
public class OptimizeIndexAction extends AbstractIndexAction implements IndexAction {

    private static final Log LOG = LogFactory.getLog(OptimizeIndexAction.class);

    private final AtomicBoolean optimizerIsBusy = new AtomicBoolean();

    @Override
    public void performAction(final LuceneWork work) {
        final boolean acquired = optimizerIsBusy.compareAndSet(false, true);
        if (acquired) {
            try {
                writer.forceMerge(1, true);
            } catch (final IOException e) {
                final String message = "Unable to optimize directory: " + writer.getDirectory();
                throw new SearchException(message, e);
            } finally {
                optimizerIsBusy.set(false);
            }
        } else {
            LOG.debug("Skipping optimization on index " + writer.getDirectory()
                    + " as it is already being optimized");
        }
    }

}
